const isFunction = val => (typeof val === 'function');

//发起请求
const request = (url, params, success, error, complete) => {
  wx.request({
    url: url,
    method: params.method || 'POST',
    data: params.data || {},
    header: {'content-type': 'application/x-www-form-urlencoded'},
    success: function(res) {
      isFunction(success) && success(res)
    },
    fail: function(res) {
      isFunction(error) && error(res)
    },
    complete: function(res) {
      isFunction(complete) && complete(res)
    }
  })
}

//单文件上传
const upload = (url, params, success, error, complete) => {
  wx.uploadFile({
    url: url,
    filePath: params.filePath,
    name: params.name,
    header: { 'content-type': 'application/x-www-form-urlencoded' },
    success: function (res) {
      isFunction(success) && success(res)
    },
    fail: function (res) {
      isFunction(error) && error(res)
    },
    complete: function (res) {
      isFunction(complete) && complete(res)
    }
  })
}

/**多文件上传
 * url String 目标地址
 * params Object 需要上传的参数
 * params.filePath Array 包含文件路径的数组
 * params.name String 文件name
 * successUp Number 上传成功的数量
 * failUp Number 上传失败的数量
 * index Number 当前上传的文件下标
 * length Number 文件总数
 * success Function 上传成功的回调函数
 * fail Function 上传失败的回调函数
 * complete Function 上传完成的回调函数
 */
const uploadMulti = (url, params, successUp, failUp, index, length, success, error, complete) => {
  wx.uploadFile({
    url: url,
    filePath: params.filePath[index],
    name: params.name,
    header: { 'content-type': 'application/x-www-form-urlencoded' },
    success: function (res) {
      successUp ++;
      isFunction(success) && success(res, index)
    },
    fail: function (res) {
      failUp ++;
      isFunction(error) && error(res)
    },
    complete: function (res) {
      index ++;
      if(index == length) {
        wx.showToast({
          title: '上传完成！总共' + successUp + '张上传成功，' + failUp + '张上传失败。',
          icon: 'none',
          duration: 3000
        })
      }else {
        uploadMulti(url, params, successUp, failUp, index, length, success, error, complete);
      }
      
      isFunction(complete) && complete(res)
    }
  })
}

module.exports = {
  request,
  upload,
  uploadMulti,
  isFunction
}